﻿using System;
using System.Web.Mvc;

using mvcForum.Web.Controllers;
using System.Net;
using mvcForum.Core;
using mvcForum.Core.Specifications;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class BanIPController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Add(String ip, String mode) {
			IPAddress address;
			if (String.IsNullOrEmpty(ip) || !IPAddress.TryParse(ip, out address)) {
				// TODO: error!
				return new HttpStatusCodeResult(500, "Invalid IP address");
			}

			this.GetRepository<BannedIP>().Create(new BannedIP { IP = address.ToString(), Timestamp = DateTime.UtcNow });
			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Remove(String ip, String mode) {
			IPAddress address;
			if (String.IsNullOrEmpty(ip) || !IPAddress.TryParse(ip, out address)) {
				// TODO: error!
				return new HttpStatusCodeResult(500, "Invalid IP address");
			}
			IRepository<BannedIP> bipRepo = this.GetRepository<BannedIP>();
			BannedIP bip = bipRepo.ReadOne(new BannedIPSpecifications.SpecificIP(address.ToString()));
			if (bip != null) {
				bipRepo.Delete(bip);
				this.Context.SaveChanges();
			}

			return new HttpStatusCodeResult(200);
		}

		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult CheckStatus(String ip, String mode) {
			IPAddress address;
			if (String.IsNullOrEmpty(ip) || !IPAddress.TryParse(ip, out address)) {
				// TODO: error!
				return new HttpStatusCodeResult(500, "Invalid IP address");
			}

			Boolean banned = (this.GetRepository<BannedIP>().ReadOne(new BannedIPSpecifications.SpecificIP(address.ToString())) != null);

			return this.CustomJson(new { Banned = banned });
		}
	}
}